package com.glink.manage.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.glink.common.util.LogUtil;
import com.glink.manage.common.Constants;
import com.glink.manage.common.enums.MqttEnum;
import com.glink.manage.dto.barriergate.*;
import com.glink.manage.service.BarrierGateService;
import com.glink.manage.service.PersonSyncRecordService;
import com.glink.manage.vo.barriergate.DeviceLoginVO;
import com.glink.manage.vo.barriergate.DeviceNotifyVO;
import com.glink.manage.vo.barriergate.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;

@Slf4j
@RestController
@RequestMapping()
@Api(tags = "道闸设备接入管理")
public class BarrierGateLanYiController {

    @Autowired
    protected MessageSource messageSource;
    
    @Autowired
    private BarrierGateService barrierGateService;

    @Autowired
    private PersonSyncRecordService personSyncRecordService;
    
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "01.行人道闸-联义-登录", notes = "01.行人道闸-登录")
    @PostMapping(value = "/device/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceLoginVO findBarriersPagePeople(@RequestBody @Validated DeviceLoginDTO dto) {
        log.info("01.行人道闸-联义-登录:{}", dto);
        DeviceLoginVO deviceLoginVO = barrierGateService.login_lianYi(dto);
        log.info("01.行人道闸-联义-登录: success");
        return deviceLoginVO;
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "02.行人道闸-联义-获取人员信息", notes = "02.行人道闸-获取人员信息")
    @PostMapping(value = "/device/sync_person", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultVO syncPerson(@RequestBody @Validated DeviceSyncPersonDTO dto) {
        log.info("02.行人道闸-联义-获取人员信息:{}", dto);
        try {
            ResultVO resultVO = barrierGateService.syncPerson_lianYi(dto);
            log.info("02.行人道闸-联义-获取人员信息: success");
            return resultVO;
        }catch (Exception e){
            log.error("02.行人道闸-联义-获取人员信息，异常", e);
            ResultVO resultVO = new ResultVO();
            resultVO.setCode(MqttEnum.RequestCode.DATA_ERROR.getCode());
            resultVO.setMsg(MqttEnum.RequestCode.DATA_ERROR.getMsg());
            resultVO.setSuccess(true);
            return resultVO;
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "03.行人道闸-联义-反馈执行结果", notes = "03.行人道闸-反馈执行结果")
    @PostMapping(value = "/device/notify", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO deviceNotify(@RequestBody @Validated DeviceNotifyDTO dto) {
        log.info("03.行人道闸-联义-反馈执行结果:{}", dto);
        DeviceNotifyVO deviceNotifyVO = barrierGateService.deviceNotify_lianYi(dto);
        log.info("03.行人道闸-联义-反馈执行结果: success");
        return deviceNotifyVO;
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "04.行人道闸-联义-同步对比记录", notes = "04.行人道闸-同步对比记录")
    @PostMapping(value = "/record/upload/online", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO recordUploadOnline(@RequestBody @Validated RecordUploadOnlineDTO dto) {
        log.info("04.行人道闸-联义-同步对比记录:{}", dto);
        try {
            DeviceNotifyVO deviceNotifyVO = barrierGateService.recordUploadOnline_lianYi(dto);
            log.info("04.行人道闸-联义-同步对比记录: success");
            return deviceNotifyVO;
        }catch (Exception e){
            log.error("04.行人道闸-联义-同步对比记录，异常", e);
            DeviceNotifyVO resultVO = new DeviceNotifyVO();
            resultVO.setCode(MqttEnum.RequestCode.DATA_ERROR.getCode());
            resultVO.setMsg(MqttEnum.RequestCode.DATA_ERROR.getMsg());
            resultVO.setSuccess(true);
            return resultVO;
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "05.行人道闸-联义-获取设备人员列表", notes = "05.行人道闸-获取设备人员列表")
    @PostMapping(value = "/device/get_person_all", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO getPersonAll(@RequestBody @Validated DeviceGetPersonAllDTO dto) {
        log.info("05.行人道闸-联义-获取设备人员列表:{}", dto);
        DeviceNotifyVO deviceNotifyVO = new DeviceNotifyVO();
        deviceNotifyVO.setCode(MqttEnum.RequestCode.SUCCESS.getCode());
        deviceNotifyVO.setMsg(MqttEnum.RequestCode.SUCCESS.getMsg());
        deviceNotifyVO.setSuccess(true);
        return deviceNotifyVO;
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "05-1.行人道闸-联义-获取设备人员列表", notes = "05-1.行人道闸-获取设备人员列表")
    @PostMapping(value = "/device/get_person", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO get_person(@RequestBody Object dto) {
        log.info("05-1.行人道闸-联义-获取设备人员列表:{}", dto);
        DeviceNotifyVO deviceNotifyVO = new DeviceNotifyVO();
        deviceNotifyVO.setCode(MqttEnum.RequestCode.SUCCESS.getCode());
        deviceNotifyVO.setMsg(MqttEnum.RequestCode.SUCCESS.getMsg());
        deviceNotifyVO.setSuccess(true);
        return deviceNotifyVO;
    }

    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "06.行人道闸-联义-一致性指令", notes = "06.行人道闸-一致性指令")
    @PostMapping(value = "/device/checkConsistency", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO checkConsistency(@RequestBody @Validated DeviceCheckConsistencyDTO dto) {
        log.info("06.行人道闸-联义-一致性指令:{}", dto);
        DeviceNotifyVO deviceNotifyVO = new DeviceNotifyVO();
        deviceNotifyVO.setCode(MqttEnum.RequestCode.SUCCESS.getCode());
        deviceNotifyVO.setMsg(MqttEnum.RequestCode.SUCCESS.getMsg());
        deviceNotifyVO.setSuccess(true);
        return deviceNotifyVO;
    }

    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "07.行人道闸-联义-人员详情", notes = "07.行人道闸-人员详情")
    @PostMapping(value = "/device/getPerson", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public DeviceNotifyVO getPerson(@RequestBody @Validated DeviceGetPersonDetailDTO dto) {
        log.info("07.行人道闸-联义-人员详情:{}", dto);
        DeviceNotifyVO deviceNotifyVO = new DeviceNotifyVO();
        deviceNotifyVO.setCode(MqttEnum.RequestCode.SUCCESS.getCode());
        deviceNotifyVO.setMsg(MqttEnum.RequestCode.SUCCESS.getMsg());
        deviceNotifyVO.setSuccess(true);
        return deviceNotifyVO;
    }

    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "08.行人道闸-联义-人员重新同步", notes = "08.行人道闸-人员重新同步")
    @PostMapping(value = "/device/afreshSync", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void afreshSync(@RequestBody @Validated DeviceGetDevSnoDTO dto) {
        log.info("08.行人道闸-联义-人员重新同步:{}", dto);
        // 记录是否首次登录
        Constants.firstSyncByBarrierGatePersonList.add(dto.getDevSno());
        
        // 删除当前设备的所有同步记录
        personSyncRecordService.removeByDevSno(dto.getDevSno());
        
        // 重新同步
        barrierGateService.issuingPerson(dto.getDevSno());
        
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public DeviceNotifyVO handleException(Exception e) {
        log.error("Exception {}", LogUtil.encode(e));
        log.error("Exception", e);
        if(e.getMessage().contains("validation")){
            // 处理form表单提交，抛出的异常
            String[] split = e.getMessage().split("default message", -1);
            if(split.length > 0 && !StringUtils.isEmpty(split[0])){
                String errorMsg = split[split.length - 1];
                return new DeviceNotifyVO(100002, errorMsg, false);
            }
        }else if(e.getMessage().contains("jdbc.exception")){
            return new DeviceNotifyVO(200001, e.getMessage(), false);
        }else if(e.getMessage().contains("java.sql.SQL") || e.getMessage().contains("Data truncation")){
            return new DeviceNotifyVO(200001, "数据库操作失败", false);
        }
        String msg = this.messageSource.getMessage("300001", null, Locale.getDefault());
        return new DeviceNotifyVO(300001, msg, false);
    }
}
